package com.xkdx.guangguang.fragment.my.setup;

import java.util.HashMap;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.pay.PayAction;
import com.xkdx.guangguang.fragment.my.pay.PayFragment;
import com.xkdx.guangguang.fragment.my.pay.PayModule;
import com.xkdx.guangguang.fragment.my.pay.PayPresistence;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.presistence.exchangeproduct.ExchangeProductAction;
import com.xkdx.guangguang.presistence.exchangeproduct.ExchangeProductModule;
import com.xkdx.guangguang.presistence.exchangeproduct.ExchangeProductModule.ExchangePoint;
import com.xkdx.guangguang.presistence.exchangeproduct.ExchangeProductPresistence;
import com.xkdx.guangguang.shareclass.ProductInfo;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class MyIntegralexChangeFrament extends BaseFragment implements
		OnClickListener {
	View view;
	Button back;
	ImageView exchange, imagefocus; // 兑换按钮
	String ProductID, ProductCode, ProductScroe; // 商品ID
	Boolean isBuy = false;
	TextView prodcutname, pinming, shopname, address, score, phone;
	private String image_url = "";
	String userID, loginToken;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	ProgressBar pb;
	TextView mypoint, remain_num;
	MyIntegralexChangeAction myIntegralexChangeAction;
	MyIntegralexChangeModule myIntegralexChangeModule;
	MyIntegralexChnagePresistence myIntegralexChnagePresistence;
	ProductInfo productInfo;
	ExchangePoint exchangePoint;

	ExchangeProductAction exchangeProductAction;
	ExchangeProductModule exchangeProductModule;
	ExchangeProductPresistence exchangeProductPresistence;

	PayAction payAction;
	PayModule payModule;
	PayPresistence payPresistence;
	SharePrefenceUtil su;
	private SharePrefenceUtil sp_product;
	private String pos_trace;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ProductID = getArguments() != null ? getArguments().getString(
				"ProductID") : "";

//		sp_product = new SharePrefenceUtil(getActivity(), IConstants.SP_POS);
//		pos_trace = sp_product.getPosTrace();

		su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		loginToken = new SharePrefenceUtil(getActivity(), IConstants.SP_USER)
				.getUserLoginToken();
		String Type = getArguments().getString("Type");
		if (Type.equals("3")) {
			isBuy = true;
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.my_integralexchange, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		back = (Button) view.findViewById(R.id.my_integralexchange_back);
		exchange = (ImageView) view
				.findViewById(R.id.my_integralexchange_btnduihuan);
		prodcutname = (TextView) view
				.findViewById(R.id.my_integralexchange_brandname);
		pinming = (TextView) view
				.findViewById(R.id.my_integralexchange_pinming);
		shopname = (TextView) view
				.findViewById(R.id.my_integralexchange_shangjia);
		address = (TextView) view
				.findViewById(R.id.my_integralexchange_address);
		score = (TextView) view.findViewById(R.id.my_integralexchange_jifen);
		phone = (TextView) view
				.findViewById(R.id.my_integralexchange_customerservicephone);
		imagefocus = (ImageView) view
				.findViewById(R.id.my_integralexchange_imfocus);
		mypoint = (TextView) view
				.findViewById(R.id.my_integralexchange_mypoint);
		remain_num = (TextView) view
				.findViewById(R.id.my_integralexchange_Remain_Num);
		pb = (ProgressBar) view.findViewById(R.id.mychange_pb);
		if (isBuy) {
			exchange.setImageResource(R.drawable.pay);
		}

		myIntegralexChangeAction = new MyIntegralexChangeAction(ProductID);
		myIntegralexChangeModule = new MyIntegralexChangeModule();
	}

	@Override
	public void setOnClick() {
		back.setOnClickListener(this);
		exchange.setOnClickListener(this);

	}

	@Override
	public void showLoading() {
		dataLoadDialog.show();
		myIntegralexChnagePresistence = new MyIntegralexChnagePresistence(this);
		myIntegralexChnagePresistence.setActitons(myIntegralexChangeAction);
		myIntegralexChnagePresistence.setModule(myIntegralexChangeModule);
		myIntegralexChnagePresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (myIntegralexChnagePresistence != null) {
					myIntegralexChnagePresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.my_integralexchange_back:
			getFragmentManager().popBackStack();
			break;
		case R.id.my_integralexchange_btnduihuan:
			loginToken = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER).getUserLoginToken();
			if (loginToken.equals("")) {
				SelfUserLogin();
			} else {
				if (isBuy) {
					int num = Integer.valueOf(productInfo.getRemain_Num());
					if (num <= 0) {
						Toast.makeText(getActivity(), "暂时无货",
								Toast.LENGTH_SHORT).show();
					} else {
						pay();
					}
				} else {
					dataLoadDialog.show();

					exchangeProductAction = new ExchangeProductAction(
							productInfo.getProductID(),
							productInfo.getProductScore(),
							su.getUserLoginToken(), su.getUserID(),
							productInfo.getProductCode());
					exchangeProductModule = new ExchangeProductModule();
					exchangeProductPresistence = new ExchangeProductPresistence(
							this);
					exchangeProductPresistence
							.setActitons(exchangeProductAction);
					exchangeProductPresistence.setModule(exchangeProductModule);
					exchangeProductPresistence.execute();
				}
			}
			break;

		default:
			break;
		}

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			productInfo = myIntegralexChangeModule.productInfo;
			setValues();
		} else {
			refresh(map);
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			exchangePoint = exchangeProductModule.exchangePoint;
			if (exchangePoint.getStatus().equals("Success")) {
				exchangeSucess();
			} else {
				Toast.makeText(getActivity(), "兑换失败", Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			showErrorTip(map);
		}
	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		if (map.containsKey("0")) {
			if (!payModule.CCB_FOR_PAY_URL.equals("")) {
				
				IConstants.POS_FROMWHERE = "baoxiang";
				PayFragment payFragment = new PayFragment();

				Bundle b = new Bundle();
				b.putString("paycode", payModule.CCB_FOR_PAY_URL);
				b.putString("ProductsID", ProductID);
				payFragment.setArguments(b);
				getFragmentManager().beginTransaction()
						.replace(R.id.fragment, payFragment)
						.addToBackStack(null).commit();
			} else {
				Toast.makeText(getActivity(), payModule.message,
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	// 填充详情信息
	protected void setValues() {

		prodcutname.setText("商品: "
				+ (productInfo.getProductName() != null ? productInfo
						.getProductName() : ""));
		pinming.setText((productInfo.getProductCode() != null ? productInfo
				.getProductCode() : ""));
		shopname.setText((productInfo.getShopName() != null ? productInfo
				.getShopName() : ""));
		address.setText((productInfo.getShopAddress() != null ? productInfo
				.getShopAddress() : ""));

		int num = Integer
				.parseInt(productInfo.getRemain_Num() != null ? productInfo
						.getRemain_Num() : "0");
		if (isBuy) {
			remain_num.setText("当前剩余数量:   " + num);
			score.setText("商品价格："
					+ (productInfo.getProductPrice() != null ? productInfo
							.getProductPrice() : "") + "元");
			if (num <= 0) {
				exchange.setImageResource(R.drawable.pay_unselected);
			}
		} else {
			remain_num.setText("当前可兑换数量: " + num);
			score.setText("所需积分: "
					+ (productInfo.getProductScore() != null ? productInfo
							.getProductScore() : ""));
		}
		phone.setText(productInfo.getShopTel() != null ? productInfo
				.getShopTel() : "");

		if (getActivity() != null) {
			SharePrefenceUtil su_user = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			if (su_user.getUserPoint() != null)
				mypoint.setText("您当前的积分: " + su_user.getUserPoint());
		}

		if ("1".equals(productInfo.getExchange())) {
			exchange.setVisibility(View.VISIBLE);
		}

		if (productInfo.getPictureList() != null
				&& productInfo.getPictureList().size() > 0) {
			if (productInfo.getPictureList().get(0) != null
					&& !("".equals(productInfo.getPictureList().get(0)))) {
				image_url = IConstants.addSuffix(productInfo.getPictureList()
						.get(0), "_BigView");
				Log.i("积分", image_url);
				imageLoader.displayImage(image_url, imagefocus, options,
						new ImageLoadingListener() {

							@Override
							public void onLoadingStarted(String imageUri,
									View view) {
								pb.setVisibility(View.VISIBLE);
							}

							@Override
							public void onLoadingFailed(String imageUri,
									View view, FailReason failReason) {

							}

							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								if (pb != null && pb.isShown()) {
									pb.setVisibility(View.GONE);
								}
							}

							@Override
							public void onLoadingCancelled(String imageUri,
									View view) {

							}
						});
			}
		} else {
			pb.setVisibility(View.INVISIBLE);

		}

	}

	private void exchangeSucess() {

		Toast.makeText(getActivity(), "兑换成功", Toast.LENGTH_SHORT).show();
		SharePrefenceUtil su_user = new SharePrefenceUtil(getActivity(),
				IConstants.SP_USER);
		su_user.setUserPoint(exchangePoint.getUserPoint());
		mypoint.setText("您当前的积分: " + su_user.getUserPoint());

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage("兑换成功");
		builder.setPositiveButton("去领取", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ExchangeListFragment exchangeListFragment = new ExchangeListFragment();
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.addToBackStack(null);
				ft.replace(R.id.fragment, exchangeListFragment);
				ft.commit();
			}
		});
		builder.setNegativeButton("确定", null);
		builder.create().show();

	}

	private void pay() {
//		saveProductStatic();

		PayFragment.isBack = false;
		payAction = new PayAction(loginToken, ProductID, su.getUserID(),"1");
		payModule = new PayModule();
		payPresistence = new PayPresistence(this);
		payPresistence.setActitons(payAction);
		payPresistence.setModule(payModule);
		payPresistence.execute();

	}

//	private void saveProductStatic() {

//		int result_num = 1;
//		float unit_price = Float.parseFloat(productInfo.getProductPrice());
//		float sum = unit_price * result_num;
//
//		productInfo.setOrder_Num(result_num + "");
//		productInfo.setProductTotalPrice(sum + "");
//		productInfo.setProductPosTrace(sp_product.getPosTrace());

//		IConstants.ProductStatic = productInfo;
//	}

}
